//
//  SLAddLockScanVC.m
//  SlockApp
//
//  Created by 凯朱 on 2024/7/16.
//

#import "SLConnectBridgeVC.h"
#import "SLAddLockListCell.h"
#import <SlockApp-Swift.h>

static  NSString *const kCellId = @"SLAddLockListCell";
@interface SLConnectBridgeVC ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong)NSMutableArray *dataArray;
@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)LottieAnimationView *animation;
@end

@implementation SLConnectBridgeVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUpSubViews];
    self.icon.image = nil;
    [self refreshConnectWifi];
}

-(void)setUpSubViews{
    self.title = kLocalString(@"Add bridge");
    _sureBtn.btnStyle = 1;
    _sureBtn.hidden = YES;
}

#pragma mark -- 连接wifi
-(void)refreshConnectWifi{
    _animation = [AnimationLoader loadAnimationRepeatAndPlayFrom:@"Wifi-connecting" into:self.icon];
    _tabBgView.hidden = YES;
    _topLbl.text = kLocalString(@"Connecting...");
    _sureBtn.hidden = YES;
    //修改wifi
    if (_bridgeDetailVc) {
        NSDictionary *params = @{
            @"deviceNo":kCurClickDevice.deviceNo,
            @"ssid":_ssid,
            @"password":_pswd,
            @"timeout":@(90),
        };
        [ZKHttpManager postWithPath:@"/msl_user/changeWifi" timeout:90 params:params finished:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull code, NSString * _Nonnull message) {
            if (!isSuccessed) {
                [self refreshWithConnectResult:NO];
                return;
            }
            [self refreshWithConnectResult:YES];
        }];
    }
    //第一次给网关配网
    else{
        [[SLBluetoothManager sharedManager] setGateStartConnectWifiWith:^(NSString *commond, BOOL isSuccess, id data, NSString *errorMsg) {
            if (!isSuccess) {
                [self refreshWithConnectResult:NO];
                return;
            }
            //连接成功
            [self refreshWithConnectResult:YES];
        }];
    }
}

-(void)refreshWithConnectResult:(BOOL)isSuccess{
    self->_sureBtn.hidden = NO;
    if (isSuccess) {
        self->_topLbl.text = kLocalString(@"Connected.");
        self->_animation = [AnimationLoader loadAnimationFrom:@"Wifi-success" into:self.icon];
        [AnimationLoader playAnimationWithAnimationView:self->_animation for:1];
        [self->_sureBtn setTitle:kLocalString(@"Done") forState:UIControlStateNormal];
    }else{
        self->_topLbl.text = kLocalString(@"Connecting faild");
        [self->_sureBtn setTitle:kLocalString(@"Retry") forState:UIControlStateNormal];
        self->_animation = [AnimationLoader loadAnimationFrom:@"Wifi-failed" into:self.icon];
        [AnimationLoader playAnimationWithAnimationView:self->_animation for:1];
    }
}

- (IBAction)sureAction:(UIButton *)sender {
    if ([sender.titleLabel.text isEqualToString:kLocalString(@"Retry")]) {
        [self refreshConnectWifi];
    }else{
        //从详情进来的
        if (_bridgeDetailVc) {
            [self.navigationController popToViewController:_bridgeDetailVc animated:YES];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                if (self.refreshBlock) self.refreshBlock();
            });
        }else{
            [SLTipAlertView showWith:kLocalString(@"Need to add a new padlock right now?") content1:kLocalString(@"Press 'Add new device' to search and compare new padlocks now.") content2:@"" doneBtn:kLocalString(@"Add new device") cancelBtn:kLocalString(@"Not now") action:^(NSInteger index) {
                if (index == 0) {
                    [self.navigationController popToRootViewControllerAnimated:YES];
                    return;
                }
            }];
        }
    }
}

-(void)startConnect{
    _tabBgView.hidden = YES;
    _topLbl.text = kLocalString(@"Connecting...");
    _sureBtn.hidden = YES;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self connectSuccess];
    });
}

-(void)connectSuccess{
    _sureBtn.hidden = NO;
    _topLbl.text = kLocalString(@"Completed!");
    _icon.image = [UIImage imageNamed:@"icon_bridge_connect_finish"];
    [_sureBtn setTitle:kLocalString(@"Done") forState:UIControlStateNormal];
}


#pragma mark - ================<tableViewDataSource>===============
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 5;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    SLAddLockListCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellId];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    SLLockModel *model = [[SLLockModel alloc] init];
    model.deviceCategory = @"1";
    cell.model = model;
    return cell;
}

#pragma mark - ================<UITableViewDelegate>===============
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 100;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 20;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UITableViewHeaderFooterView *headview = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"head"];
    if (!headview) {
        headview = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:@"head"];
        headview.frame = CGRectMake(0, 0, kScreenWidth, 20);
        headview.contentView.backgroundColor = KClearColor;
    }
    return headview;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UITableViewHeaderFooterView *footerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"foot"];
    if (!footerView) {
        footerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:@"foot"];
        footerView.frame = CGRectMake(0, 0, kScreenWidth, 0.1);
        footerView.contentView.backgroundColor = KClearColor;
    }
    return footerView;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [self startConnect];
    
}

#pragma mark - ================<懒加载>===============
-(UITableView *)tableView{
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.estimatedRowHeight = 100;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerNib:[UINib nibWithNibName:kCellId bundle:nil] forCellReuseIdentifier:kCellId];
        _tableView.backgroundColor = KClearColor;
    }
    return _tableView;
}

-(NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}

@end
